import './userEdit.less'
import { TreeToArray } from '@/utils'

import userManageMixin from '@/mixins/userManage'
import dictsMixin from '@/mixins/dicts'
export default {
    mixins: [userManageMixin, dictsMixin],
    data() {
        return {
            title: '',
            userDetail: {
                name: ''
            },
            form: {
                ref: 'userEditForm',
                rules: {
                    name: [
                        { required: true, message: '请输入用户姓名', trigger: 'blur' }
                    ]
                },
                timer: null,
                // 用户姓名
                searchList: [],
                loading: false,

                // 角色
                selectedRoles: [],

                // 监察产品类型
                selectedProducts: [],

                // 组织架构
                defaultCheckedId: [],
                deptJcList: [],
                defaultProps: {
                    value: 'name',
                    label: 'name',
                    children: 'children'
                },
                selectedOrgs: {
                    ids: [],
                    names: []
                }
            }
        }
    },
    computed: {
        userId() {
            return this.$route.query.userid || 0
        },
        deptId() {
            return this.$route.query.deptid || 0
        },
        // 角色树列表
        roleTree() {
            return this.$store.state.system.roleList
        },
        // 角色列表
        roleList() {
            return TreeToArray({ tree: this.$store.state.system.roleList })
        }
    },
    mounted() {
        this.title = this.userId ? '修改用户' : '添加用户'
        this.$store.dispatch('setBreadData', [
            {
                name: '系统管理'
            },
            {
                name: '用户管理',
                path: '/system/user?id=' + this.deptId
            },
            {
                name: this.title
            }
        ])
        if (this.userId) {
            this.getUserDetail()
        }
        else {
            this.userDetail.password = '123@abc'
        }
        // 角色
        if (this.$store.state.system.roleList && this.$store.state.system.roleList.length == 0) {
            this.$store.dispatch('getRoleList')
        }
        // 区域
        this.getArea()
    },
    methods: {
        // 获取用户详情
        getUserDetail() {
            api.getUserDetail({
                id: this.userId
            }).then(data => {
                this.userDetail = data

                this.form.selectedRoles = []
                if (data.roles) {
                    data.roles.forEach((item) => {
                        this.form.selectedRoles.push(item.name)
                    })
                }

                this.form.selectedProducts = []
                if (data.products) {
                    data.products.forEach((item) => {
                        this.form.selectedProducts.push(item.name)
                    })
                }

                this.form.selectedOrgs.ids = []
                this.form.selectedOrgs.names = []
                if (data.sales) {
                    data.sales.forEach((item) => {
                        this.form.selectedOrgs.ids.push(item.code)
                        this.form.selectedOrgs.names.push(item.name)
                        this.form.defaultCheckedId.push(item.code)
                    })
                }
            })
        },
        // 搜索用户
        searchUserMethod(val) {
            if (this.form.timer) {
                clearTimeout(this.form.timer)
            }
            if (val !== '') {
                this.form.loading = true;
                this.form.timer = setTimeout(() => {
                    api.getOrgUserList({
                        userName: val,
                        pageSize: 100,
                        pageIndex: 1
                    }).then(res => {
                        this.form.loading = false
                        this.form.searchList = res.list
                    }).catch(res => {
                        console.log(res)
                    })
                }, 200)
            } else {
                this.form.searchList = []
            }
        },
        // 选择用户
        selectUser(id) {
            let obj = this.form.searchList.find(item => item.id == id)
            if (!obj) return
            this.userDetail.name = obj.userName
            this.userDetail.username = obj.email
            this.userDetail.email = obj.email
            this.userDetail.companyName = '深圳达飞金融控股有限公司'
            this.userDetail.departmentName = obj.deptName
            this.userDetail.departmentCode = obj.salesDeptCode
            this.userDetail.position = obj.position
            this.userDetail.phone = obj.phone
            this.userDetail.identity = obj.identity
            this.userDetail.remark = obj.remark
        },
        // 组织架构
        loadOrgList(node, resolve) {
            this.$store.dispatch('getOrgList', {
                data: {
                    parentCode: node.data ? node.data.deptCode : 0
                },
                callback(data) {
                    if (data && data.length > 0) {
                        resolve(data)
                    }
                    else {
                        if (node) {
                            resolve([])
                        }
                    }
                }
            })
        },
        // 查询部门区域（grade：等级 1 分部，2 大区， 3 区域）
        getArea() {
            this.form.deptJcList = []
            api.getArea({ grade: 3 })
                .then(res => {
                    res.forEach((ele) => {
                        ele.children = []
                        this.form.deptJcList.push(ele)
                    })
                    console.log()
                })
                .catch(err => {
                    console.log(err)
                })
        },
        // 获取营业部
        getDeptJc(val) {
            if (val) {
                var _name = val[0]
                let _index = 0
                for (let i = 0; i < this.form.deptJcList.length; i++) {
                    if (this.form.deptJcList[i].name == _name) {
                        _index = i
                        break
                    }

                }
                setTimeout(() => {
                    let _data = {}
                    _data.qyName = _name
                    _data.pageBean = {}
                    _data.pageBean.pageIndex = 1
                    _data.pageBean.pageSize = 1000
                    api.queryDeptJc(_data)
                        .then(res => {
                            this.form.deptJcList[_index].children = []
                            res.list.map((d) => {
                                this.form.deptJcList[_index].children.push({
                                    id: d.id,
                                    name: d.deptName
                                })
                            })
                        })
                        .catch(err => {
                            console.log(err)
                        })
                }, 300)
            }
        },
        // 获取营业部
        deptJcChange(val) {
            if (val.length > 1) {
                let _index = 0
                for (let i = 0; i < this.form.deptJcList.length; i++) {
                    if (this.form.deptJcList[i].name == val[0]) {
                        _index = i
                        break
                    }
                }
                var _dept = this.form.deptJcList[_index].children.find(item => item.name == val[1])
                if (_dept) {
                    if (this.form.selectedOrgs.ids.indexOf(_dept.id) == -1) {
                        this.form.selectedOrgs.ids.push(_dept.id)
                        this.form.selectedOrgs.names.push(val[1])
                    }
                }
            }
        },
        // 选择组织架构
        orgCheckChange(data, check) {
            var _index = this.form.selectedOrgs.ids.indexOf(data.deptCode)
            if (check) {
                if (_index == -1) {
                    this.form.selectedOrgs.ids.push(data.deptCode)
                    this.form.selectedOrgs.names.push(data.deptName)
                }
            }
            else {
                if (_index > -1) {
                    this.form.selectedOrgs.ids.splice(_index, 1)
                    this.form.selectedOrgs.names.splice(_index, 1)
                }
            }
        },
        // 移除负责内容
        closeOrg(index) {
            this.form.selectedOrgs.ids.splice(index, 1)
            this.form.selectedOrgs.names.splice(index, 1)
            // this.form.defaultCheckedId.splice(index, 1)
            // this.$refs.treeDept.setCheckedKeys(this.form.selectedOrgs.ids)
        },
        // 清空负责内容
        clearOrg() {
            this.form.selectedOrgs.ids = []
            this.form.selectedOrgs.names = []
            // this.form.defaultCheckedId = []
            // this.$refs.treeDept.setCheckedKeys([])
        },
        // 返回
        goBack() {
            this.$router.go(-1)
        },
        // 保存
        sumbitForm() {
            this.$refs[this.form.ref].validate((valid) => {
                if (valid) {
                    if (this.checkRole() && this.checkProduct()) {
                        this.editUserDetail()
                    }
                } else {
                    this.$msg.error('表单验证失败!')
                }
            })
        },
        //编辑用户
        editUserDetail() {
            var _this = this
            this.userDetail.depts = []
            if (this.deptId) {
                this.userDetail.depts.push(this.deptId)
            }
            this.userDetail.sales = this.form.selectedOrgs.ids
            api.editUser({
                type: this.userId ? 1 : 0,
                data: this.userDetail
            }).then(res => {
                if (this.userId) {
                    this.$msg.success('修改成功')
                }
                else {
                    this.$msg.success('添加成功')
                }
                this.$router.go(-1)
            }).catch(res => {
                console.log(res)
            })
        },
        // 验证角色
        checkRole() {
            if (this.form.selectedRoles.length == 0) {
                this.$msg.error('请选择勾选角色!')
                return false
            }
            else {
                this.userDetail.roles = []
                this.form.selectedRoles.forEach((item) => {
                    let _obj = this.roleList.find((a) => {
                        return a.name == item
                    })
                    this.userDetail.roles.push(_obj.id)
                })
                return true
            }
        },
        // 验证所监察产品类型
        checkProduct() {
            if (this.form.selectedProducts.length == 0) {
                this.$msg.error('请选择勾选所监察产品类型!')
                return false
            }
            else {
                this.userDetail.products = []
                this.form.selectedProducts.forEach((item) => {
                    let _obj = this.dicts.productType.find((a) => {
                        return a.name == item
                    })
                    this.userDetail.products.push(_obj.id)
                })
                return true
            }
        }
    }
}